package com.xingxue.web;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.xingxue.entity.User;
import com.xingxue.service.UserService;
import com.xingxue.service.UserServiceImpl;
import com.xingxue.util.DigestUtil;
import com.xingxue.util.JdbcUtil;

@SuppressWarnings("serial")
@WebServlet("/login")
public class LoginController extends HttpServlet {
	
	private UserService userService = JdbcUtil.createProxy(new UserServiceImpl(), UserService.class);

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 获取参数
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String autoLogin = request.getParameter("autoLogin");
		
		System.out.println("[调试信息] email:" + email + " password:"+password + " autoLogin:" +autoLogin);	
		
		// 验证非空
		HttpSession session = request.getSession();
		if(email == null || email.trim().equals("") || password == null || password.trim().equals("")) {
			session.setAttribute("error", "您输入的用户名或密码不能为空");
			response.sendRedirect("login.jsp");
			return;
		}
		
		// 验证用户名密码
		User user = userService.findUserBy(email, password);
		if(user == null) {
			session.setAttribute("error", "您输入的用户名或密码不正确");
			response.sendRedirect("login.jsp");
			return;
		}
		
		session.setAttribute("login", true);
		// 是否勾选自动登录
		if(autoLogin != null) {
				
			// 创建token
			String token = DigestUtil.createToken();
			System.out.println("[调试信息] 已勾选自动登录,会将token[" + token + "]存入cookie和数据库");
			
			// 将token写入数据库
			userService.updateToken(email, token, UserService.EXPIRE_TIME);
			
			// 将token写入cookie
			String safe = URLEncoder.encode(email+"|"+token, "utf-8");
			Cookie c = new Cookie("token", safe);
			c.setHttpOnly(true);
			c.setMaxAge(UserService.EXPIRE_TIME);
			response.addCookie(c);
		}
		response.sendRedirect("index.jsp");
			
	}

}
